﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ice.Toolkit.Data.Entity
{
    public static class EntityAttribManager
    {
        private static Dictionary<String, Object> _dictionary = new Dictionary<String, Object>();

        public static EntityAttrib<T> Get<T>() where T : EntityBase<T>, new()
        {
            var name = typeof(T).Name;
           
            if (!_dictionary.ContainsKey(name))
            {
                 _dictionary.Add(name, new EntityAttrib<T>());
            }

            return _dictionary[name] as EntityAttrib<T>;
        }
    }
    public class EntityAttrib<T> where T : EntityBase<T>, new()
    {
        public List<KeyValuePair<String, EntityColumn>> Columns { get; private set; }
        public EntityTable Talbe { get; private set; }
        public String IdentityPropertyName { get; private set; }

        public EntityAttrib()
        {
            var entityType = typeof(T);

            foreach (var customAttrib in entityType.GetCustomAttributes(true))
            {
                if (customAttrib is EntityTable)
                {
                    Talbe = customAttrib as EntityTable;
                }
            }

            var list = new List<KeyValuePair<String, EntityColumn>>();

            foreach (var property in entityType.GetProperties())
            {
                foreach (var customAttrib in property.GetCustomAttributes(true))
                {
                    if (customAttrib is EntityColumn)
                    {
                        if ((customAttrib as EntityColumn).IsIdentity) IdentityPropertyName = property.Name;
                        list.Add(new KeyValuePair<string, EntityColumn>(property.Name, customAttrib as EntityColumn));
                        break;
                    }
                }
            }

            Columns = list;
        }
    }
}
